package cn.sam416.sample.part0303converter.conditionalgenericconverter;

import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.converter.ConditionalGenericConverter;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.Set;

public class NumberToBigDecimalConverter  implements
        ConditionalGenericConverter {
    @Override
    public boolean matches (TypeDescriptor sourceType,
                            TypeDescriptor targetType) {
        return sourceType.getType() != BigDecimal.class;
    }

    @Override
    public Set<ConvertiblePair> getConvertibleTypes () {
        return Collections.singleton(new ConvertiblePair(Number.class,
                BigDecimal.class));
    }

    @Override
    public Object convert (Object source, TypeDescriptor sourceType,
                           TypeDescriptor targetType) {

        Number number = (Number) source;
        return new BigDecimal(number.doubleValue());
    }
}
